#include "AsyncReceiver.h"

sf::Mutex m_mutex;

U2L::AsyncReceiver::AsyncReceiver(void)
{
	m_receiving = false;
	m_disconnected = false;
	m_msg.clear();
	m_socket = NULL;
}

U2L::AsyncReceiver::~AsyncReceiver(void)
{
	this->Wait();
}

void U2L::AsyncReceiver::Receive(sf::SocketTCP* _socket)
{
	if (_socket != NULL &&
		!m_receiving &&
		m_msg.empty())
	{
		m_socket = _socket;
		m_receiving = true;
		m_disconnected = false;
		this->Launch();
	}
}

bool U2L::AsyncReceiver::IsReceiving(void) const
{
	return m_receiving;
}

bool U2L::AsyncReceiver::IsDisconnected(void) const
{
	return m_disconnected;
}

std::wstring U2L::AsyncReceiver::GetMsg(void)
{
	if (!m_receiving && !m_msg.empty())
	{
		std::wstring msg = m_msg;
		m_msg.clear();
		return msg;
	}
	return std::wstring(L"");
}

void U2L::AsyncReceiver::Run(void)
{
	try
	{
		sf::Packet packet;
		if (m_socket->Receive(packet) != sf::Socket::Done)
		{
			m_disconnected = true;
		}
		else
		{
			std::wstring msg;
			packet >> msg;
			m_msg = msg;
		}
		m_socket = NULL;
		m_receiving = false;
	}
	catch (std::exception& err)
	{
		std::cerr << err.what() << std::endl;
	}
}